package com.yanqu.road.server.manger.wingroom;

import com.yanqu.road.dao.impl.wingroom.UserWingRoomPlanDaoImpl;
import com.yanqu.road.dao.impl.wingroom.UserWingRoomShareEventDaoImpl;
import com.yanqu.road.dao.impl.wingroom.WingRoomDataDaoImpl;
import com.yanqu.road.dao.impl.wingroom.chakra.WingRoomChakraDaoImpl;
import com.yanqu.road.dao.impl.wingroom.chakra.WingRoomChakraDetailDaoImpl;
import com.yanqu.road.entity.assistant.AssistantBodySkin;
import com.yanqu.road.entity.config.patrons.PatronsInfo;
import com.yanqu.road.entity.config.skill.SkillInfo;
import com.yanqu.road.entity.enums.eMessageType;
import com.yanqu.road.entity.enums.eSkillType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.LogWingRoomShareEventReward;
import com.yanqu.road.entity.player.ReturnData;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.relatives.RelativesInfo;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.entity.union.cross.CrossUnionServerGroup;
import com.yanqu.road.entity.wingroom.*;
import com.yanqu.road.entity.wingroom.chakra.data.UserWingRoomChakra;
import com.yanqu.road.entity.wingroom.chakra.data.UserWingRoomChakraDetail;
import com.yanqu.road.entity.wingroom.config.WingRoomFurnitureConfig;
import com.yanqu.road.entity.wingroom.config.WingRoomLvConfig;
import com.yanqu.road.logic.bussiness.player.UserAssistantSkinBusiness;
import com.yanqu.road.logic.bussiness.player.UserPatronsBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.wingroom.WingRoomProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.assistant.AssistantSkinModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.relatives.RelativesModule;
import com.yanqu.road.server.gameplayer.module.wingroom.WingRoomChakraModule;
import com.yanqu.road.server.gameplayer.module.wingroom.WingRoomModule;
import com.yanqu.road.server.gameplayer.module.workshop.WorkShopModule;
import com.yanqu.road.server.manger.CrossUnionServerGroupMgr;
import com.yanqu.road.server.manger.config.PatronsMgr;
import com.yanqu.road.server.manger.config.SkillMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.WorldMessageMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.relatives.RelativesMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.pb.WingRoomPb;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.yanqu.road.entity.enums.eItemId.*;

/**
 * @author ：zfr
 * @date ：2022/1/21 16:30
 */
public class WingRoomMgr extends TempMgr {
    //拜户神事件数据
    private static Map<Long, UserWingRoomShareEvent> shareEventMap = new ConcurrentHashMap<>();
    //工坊跨服同步下来的数据
    private static WingRoomProto.WorkShopPoolTemp.Builder poolMsg;
    private static Map<Long, Object> lockMap = new ConcurrentHashMap<>();

    private static boolean isAllSync;

    public static WingRoomProto.WorkShopPoolTemp.Builder getPoolMsg() {
        return poolMsg;
    }

    @Override
    public boolean reloadData() throws Exception {
        shareEventMap = new UserWingRoomShareEventDaoImpl().getUserWingRoomShareEventMap();
        return true;
    }

    @Override
    public boolean save() {
        if (shareEventMap != null) {
            for (UserWingRoomShareEvent event : shareEventMap.values()) {
                if (event.isInsertOption()) {
                    new UserWingRoomShareEventDaoImpl().add(event);
                } else if (event.isUpdateOption()) {
                    new UserWingRoomShareEventDaoImpl().update(event);
                }
            }
        }
        return true;
    }

    public static boolean checkHasCrossUnionGroup() {
        CrossUnionServerGroup unionServerGroup = CrossUnionServerGroupMgr.getServerGroupByServerId(GameServer.getInstance().getServerId());
        return unionServerGroup != null && unionServerGroup.getState() == 1;
    }

    public static void syncAllEventToCross(boolean isCrossNotify) {
        if ((!isAllSync || isCrossNotify) && checkHasCrossUnionGroup()) {
            synchronized (shareEventMap) {
                WingRoomProto.SyncCrossAllEventStatusMsg.Builder syncMsg = WingRoomProto.SyncCrossAllEventStatusMsg.newBuilder();
                for (UserWingRoomShareEvent event : shareEventMap.values()) {
                    syncMsg.addMsg(getEventStatusSyncMsg(event));
                }
                YanQuMessage message = YanQuMessageUtils.buildMessage(CrossProtocol.C_WING_ROOM_SYNC_EVENT_TO_CROSS, syncMsg);
                GamePlayerMgr.sendPacket(0, message);
            }
        }
    }

    public static void syncChangeEventToCross() {
        if (checkHasCrossUnionGroup()) {
            synchronized (shareEventMap) {
                WingRoomProto.SyncCrossAllEventStatusMsg.Builder syncMsg = WingRoomProto.SyncCrossAllEventStatusMsg.newBuilder();
                for (UserWingRoomShareEvent event : shareEventMap.values()) {
                    if (event.isNeedSync()) {
                        syncMsg.addMsg(getEventStatusSyncMsg(event));
                    }
                }
                if (syncMsg.getMsgCount() > 0) {
                    YanQuMessage message = YanQuMessageUtils.buildMessage(CrossProtocol.C_WING_ROOM_SYNC_CHANGE_EVENT_TO_CROSS, syncMsg);
                    GamePlayerMgr.sendPacket(0, message);
                }
            }
        }
    }

    public static WingRoomProto.CrossEventStatusMsg.Builder getEventStatusSyncMsg(UserWingRoomShareEvent event) {
        WingRoomProto.CrossEventStatusMsg.Builder status = WingRoomProto.CrossEventStatusMsg.newBuilder();
        status.setUserId(event.getUserId());
        status.setBeginTime(event.getLastUpdateTime());
        status.setStatus(event.getStatus());
        List<Long> getRewardUserList = event.getRewardMap().values().stream().filter(WingRoomEventReward::isGetReward).map(WingRoomEventReward::getPlayerId).collect(Collectors.toList());
        status.addAllGetRewardUser(getRewardUserList);
        event.setNeedSync(false);
        return status;
    }

    public static void syncAllEventResp() {
        isAllSync = true;
    }


    private static Object getEventLock(long userId) {
        if (!lockMap.containsKey(userId)) {
            synchronized (lockMap) {
                if (!lockMap.containsKey(userId)) {
                    lockMap.put(userId, new Object());
                }
            }
        }
        return lockMap.get(userId);
    }

    public static void addEvent(UserWingRoomShareEvent userEvent) {
        synchronized (getEventLock(userEvent.getUserId())) {
            if (!shareEventMap.containsKey(userEvent.getUserId())) {
                shareEventMap.put(userEvent.getUserId(), userEvent);
            }
        }
    }

    //事件刷新
    public static void refreshEvent(GamePlayer player) {
        synchronized (getEventLock(player.getUserId())) {
            player.getModule(WingRoomModule.class).refreshEvent();
        }
    }

    //领取自己的厢房事件的奖励
    public static ReturnData getSelfEventReward(int pos, GamePlayer player) {
        synchronized (getEventLock(player.getUserId())) {
            return player.getModule(WingRoomModule.class).getSelfEventReward(pos);
        }
    }

    //领取别人厢房事件的奖励
    public static ReturnData getOtherPlayerEventReward(long playerId, String playerName, long otherPlayerId, int pos) {
        synchronized (getEventLock(otherPlayerId)) {
            ReturnData returnData = new ReturnData(0);
            UserWingRoomShareEvent userEvent = WingRoomMgr.getUserEvent(otherPlayerId);
            if (userEvent == null) {
                returnData.setRet(GameErrorCode.E_WING_ROOM_SHARE_EVENT_NO_FOUND);
                return returnData;  //事件不存在
            }
            int ret = isDuringEventShare(userEvent, playerId);
            if (ret != 0) {
                returnData.setRet(ret);
                return returnData;
            }
            WingRoomEventReward eventReward = userEvent.getRewardMap().get(pos);
            if (eventReward == null) {
                returnData.setRet(GameErrorCode.E_WING_ROOM_SHARE_EVENT_REWARD_NO_FOUND);
                return returnData;  //奖励不存在
            }
            if (eventReward.isGetReward()) {
                returnData.setRet(GameErrorCode.E_WING_ROOM_SHARE_EVENT_REWARD_GET_ALREADY);
                return returnData;  //奖励已被领取
            }
            long nowTime = System.currentTimeMillis();
            eventReward.setGetReward(true);
            eventReward.setGetTime(nowTime);
            eventReward.setPlayerName(playerName);
            eventReward.setPlayerId(playerId);
            userEvent.setUpdateOption();

            //奖励被领光了
            if (userEvent.getRewardMap().values().stream().allMatch(WingRoomEventReward::isGetReward)) {
                userEvent.setStatus(eWingRoomEventStatus.None.getStatus());
                userEvent.setLastUpdateTime(nowTime);
                changeShareMessageStatus(userEvent);
            }
            userEvent.setNeedSync(true);
            returnData.addParam(eventReward.getReward());

            //通知主人被领奖
            GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(otherPlayerId);
            if (onlinePlayer != null) {
                onlinePlayer.getModule(WingRoomModule.class).userShareEventSync();
            }

            AutoLogMgr.add(new LogWingRoomShareEventReward(
                    playerId,
                    otherPlayerId,
                    eventReward.getReward(),
                    new Date(userEvent.getTriggerTime()),
                    new Date(userEvent.getGetRewardTime()))
            );
            return returnData;
        }
    }

    private static void changeShareMessageStatus(UserWingRoomShareEvent event) {
        String shareUnionUid = event.getShareUnionUid();
        if (StringUtils.isNullOrEmpty(shareUnionUid)) {
            WorldMessageMgr.changeWorldMessageContent(event.getUserId(), eMessageType.WingRoomWorldShare.getValue(), buildShareMessageContent(event), event.getGetRewardTime());
            return;
        }
        WorldMessageMgr.changeUnionMessageContent(event.getUserId(), eMessageType.WingRoomUnionShare.getValue(), buildShareMessageContent(event), event.getGetRewardTime(), shareUnionUid);
    }

    public static String buildShareMessageContent(UserWingRoomShareEvent event) {
        return WorldMessageMgr.encodeContent(event.getGetRewardTime(), event.getStatus() == eWingRoomEventStatus.None.getStatus() ? 0 : 1);
    }

    public static int isDuringEventShare(UserWingRoomShareEvent userEvent, long playerId) {
        if (userEvent.getStatus() < eWingRoomEventStatus.GetReward.getStatus()) {
            return GameErrorCode.E_WING_ROOM_SHARE_EVENT_GET_REWARD_LIMIT;  //其他玩家还不能领取
        }
        long nowTime = System.currentTimeMillis();
        if (userEvent.getStatus() >= eWingRoomEventStatus.GetReward.getStatus() && nowTime - userEvent.getGetRewardTime() > GameConfig.WINGROOM_FIND_FRIENDS_OTHER_PICK_UP_TIME * DateHelper.HOUR_MILLIONS) {
            return GameErrorCode.E_WING_ROOM_SHARE_EVENT_OVER_TIME;  //厢房主人领取奖励后 没分享 事件已过期
        }
        if (checkRepeatedGetReward(userEvent.getRewardMap(), playerId)) {
            return GameErrorCode.E_WING_ROOM_SHARE_EVENT_GET_REWARD_ALREADY;  //已领过奖 不能领多次奖
        }

        return 0;
    }

    //检查是否已经领过奖
    private static boolean checkRepeatedGetReward(Map<Integer, WingRoomEventReward> rewardMap, long playerId) {
        for (WingRoomEventReward eventReward : rewardMap.values()) {
            if (eventReward.isGetReward() && eventReward.getPlayerId() == playerId) {
                return true;
            }
        }
        return false;
    }

    //分享事件
    public static int shareEvent(GamePlayer player, int shareType) {
        synchronized (getEventLock(player.getUserId())) {
            return player.getModule(WingRoomModule.class).shareEvent(shareType);
        }
    }

    public static WingRoomProto.WatchOtherPlayerRespMsg.Builder getVisitMsg(long otherPlayerUserId) {
        WingRoomProto.WatchOtherPlayerRespMsg.Builder respMsg;
        GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(otherPlayerUserId);
        UserWingRoomData data;
        UserWingRoomShareEvent event = getUserEvent(otherPlayerUserId);
        AssistantBodySkin assistantBodySkin;
        UserWingRoomChakra chakra = null;
        Map<Integer, Map<Integer, Map<Integer, UserWingRoomChakraDetail>>> chakraDetailMap = new HashMap<>();
        if (onlinePlayer != null) {
            data = onlinePlayer.getModule(WingRoomModule.class).getWingRoomData();
            assistantBodySkin = onlinePlayer.getModule(AssistantSkinModule.class).getAssistantBodySkin();
            //命盘数据
            chakra = onlinePlayer.getModule(WingRoomChakraModule.class).getUserWingRoomChakra();
            chakraDetailMap = onlinePlayer.getModule(WingRoomChakraModule.class).getUserWingRoomChakraDetailMap();
        } else {
            //不在线，读取数据库
            data = new WingRoomDataDaoImpl().getUserWingRoomData(otherPlayerUserId);
            assistantBodySkin = UserAssistantSkinBusiness.getUserAssistantBodySkin(otherPlayerUserId);
            //盘数据
            chakra = new WingRoomChakraDaoImpl().getUserWingRoomChakra(otherPlayerUserId);
            chakraDetailMap = new WingRoomChakraDetailDaoImpl().getUserWingRoomChakraDetailMap(otherPlayerUserId);
        }
        if (assistantBodySkin == null) {
            assistantBodySkin = new AssistantBodySkin(0, ASSISTANT_DEFAULT_HEAD_DECORATION.getValue(), ASSISTANT_DEFAULT_FACE_DECORATION.getValue(), ASSISTANT_DEFAULT_CLOTHES_DECORATION.getValue(),
                    ASSISTANT_DEFAULT_PANTS_DECORATION.getValue(), ASSISTANT_DEFAULT_FOOT_DECORATION.getValue(), ASSISTANT_DEFAULT_HAND_DECORATION.getValue(), ASSISTANT_DEFAULT_OTHER_DECORATION.getValue(),
                    ASSISTANT_DEFAULT_SUIT.getValue());
        }
        respMsg = WingRoomPb.buildWatchOtherRespMsg(data, event, assistantBodySkin, chakra, chakraDetailMap);
        return respMsg;
    }

    public static Map<Integer, WingRoomRegion> copyPlan(long otherPlayerUserId, long otherPlayerPlanUid, WingRoomProto.GetOtherPlanRespMsg.Builder respMsg) {

        UserInfo userInfo = UserMgr.getUserInfo(otherPlayerUserId);
        if (userInfo == null) {
            return null;
        }
        respMsg.setNickName(userInfo.getNickName());
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(otherPlayerUserId);
        if (player != null) {
            UserWingRoomPlan plan = player.getModule(WingRoomModule.class).getPlan(otherPlayerPlanUid);
            if (plan == null || plan.isDelete()) {
                return null;
            }
            return plan.getRegionMap();
        }
        UserWingRoomPlan userWingRoomPlan = new UserWingRoomPlanDaoImpl().getUserWingRoomPlan(otherPlayerUserId, otherPlayerPlanUid);
        if (userWingRoomPlan != null) {
            return userWingRoomPlan.getRegionMap();
        }
        return null;
    }

    public static boolean checkEventOverTime(UserWingRoomShareEvent event) {
        long nowTime = System.currentTimeMillis();
        if (event.getStatus() == eWingRoomEventStatus.Trigger.getStatus()) {
            return nowTime - event.getTriggerTime() > TimeUnit.HOURS.toMillis(GameConfig.WINGROOM_FIND_FRIENDS_PICK_UP_TIME);
        }
        if (event.getStatus() >= eWingRoomEventStatus.GetReward.getStatus()) {
            return nowTime - event.getGetRewardTime() > TimeUnit.HOURS.toMillis(GameConfig.WINGROOM_FIND_FRIENDS_OTHER_PICK_UP_TIME);
        }
        return false;
    }

    public static void syncWorkShopPool() {
        if (poolMsg == null) {
            WingRoomProto.GetWorkShopPoolReqCrossMsg.Builder msg = WingRoomProto.GetWorkShopPoolReqCrossMsg.newBuilder();
            YanQuMessage message = YanQuMessageUtils.buildMessage(CrossProtocol.C_WING_ROOM_SYNC_WORK_SHOP_POOL, msg);
            GamePlayerMgr.sendPacket(0, message);
        }
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static UserWingRoomShareEvent getUserEvent(long userId) {
        UserWingRoomShareEvent event = shareEventMap.get(userId);
        if (event != null) {
            synchronized (getEventLock(userId)) {
                event = shareEventMap.get(userId);
                if (checkEventOverTime(event)) {
                    event.setStatus(eWingRoomEventStatus.None.getStatus());
                    event.setLastUpdateTime(System.currentTimeMillis());
                }
            }
        }
        return event;
    }

    public static void refreshWorkShopPoolMsg(WingRoomProto.WorkShopPoolTemp.Builder syncMsg) {
        if (poolMsg != null && syncMsg.getRefreshTime() <= poolMsg.getRefreshTime()) {
            return;
        }
        WingRoomProto.WorkShopPoolTemp.Builder tempMsg = WingRoomProto.WorkShopPoolTemp.newBuilder();
        tempMsg.setRefreshTime(syncMsg.getRefreshTime());
        for(WingRoomProto.WorkShopItemTemp itemMsg : syncMsg.getWorkShopItemList()){
            WingRoomFurnitureConfig furnitureConfig = WingRoomConfigMgr.getFurnitureConfig(itemMsg.getFurnitureId());
            if (null != furnitureConfig) {
                tempMsg.addWorkShopItem(itemMsg.toBuilder());
            }
        }
        poolMsg = tempMsg;
        notifyOnlinePlayer();
    }

    private static void notifyOnlinePlayer() {
        for (GamePlayer player : GamePlayerMgr.getAllOnlinePlayer()) {
            player.getModule(WorkShopModule.class).syncWorkShopPool();
        }
    }

    public static void getWingRoomFriendList(GamePlayer player) {
        WingRoomProto.GetWingRoomFriendListRespMsg.Builder respMsg = WingRoomProto.GetWingRoomFriendListRespMsg.newBuilder();
        //先亲家再商会 因为要告知是否是亲家
        Map<Long, WingRoomProto.WingRoomFriendTemp.Builder> relativeMap = new ConcurrentHashMap<>();
        WingRoomProto.GetUnionMemberEventReqCrossMsg.Builder crossReq = getWingRoomRelativeMap(player, relativeMap);
        boolean canResp = getWingRoomUnionMemMap(player, relativeMap, crossReq);
        if (!canResp) {
            return;
        }
        for (Map.Entry<Long, WingRoomProto.WingRoomFriendTemp.Builder> entry : relativeMap.entrySet()) {
            respMsg.addFriend(entry.getValue());
        }
        player.sendPacket(ClientProtocol.U_WING_ROOM_GET_FRIEND_LIST, respMsg);
    }

    private static WingRoomProto.GetUnionMemberEventReqCrossMsg.Builder getWingRoomRelativeMap(GamePlayer player, Map<Long, WingRoomProto.WingRoomFriendTemp.Builder> relativeMap) {
        Map<Long, RelativesInfo> relativesMap = player.getModule(RelativesModule.class).getRelativesMap();
        WingRoomProto.GetUnionMemberEventReqCrossMsg.Builder reqCrossMsg = WingRoomProto.GetUnionMemberEventReqCrossMsg.newBuilder();
        for (Map.Entry<Long, RelativesInfo> entry : relativesMap.entrySet()) {
            RelativesInfo relativesInfo = entry.getValue();
            long relativeUserId = entry.getKey();
            if (relativesInfo != null && relativesInfo.getStatus() == 1) {
                long serverId = RelativesMgr.getUserServerId(relativeUserId);
                if(serverId != GameServer.getInstance().getServerId()){
                    WingRoomProto.UnionMemberBaseInfoMsg.Builder builder = WingRoomProto.UnionMemberBaseInfoMsg.newBuilder();
                    builder.setUserId(relativeUserId);
                    builder.setPlayerBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(RelativesMgr.getCacheOtherServerUserMap().get(relativeUserId)));
                    builder.setRelatives(true);
                    reqCrossMsg.addMember(builder);
                    continue;
                }
                UserWingRoomShareEvent event = shareEventMap.get(relativeUserId);
                if (event == null) {
                    continue;
                }
                UserInfo relativeUserInfo = UserMgr.getUserInfo(relativeUserId);
                if (relativeUserInfo != null) {
                    WingRoomProto.WingRoomFriendTemp.Builder friendTemp = WingRoomPb.buildWingRoomFriendTemp(player.getUserId(), relativeUserId, relativeUserInfo, event, true);
                    relativeMap.put(relativeUserId, friendTemp);
                }
            }
        }
        return reqCrossMsg;
    }

    private static boolean getWingRoomUnionMemMap(GamePlayer player, Map<Long, WingRoomProto.WingRoomFriendTemp.Builder> relativeMap, WingRoomProto.GetUnionMemberEventReqCrossMsg.Builder crossReq) {
        String unionUid = player.getUserInfo().getUnionUid();
        if (StringUtils.isNullOrEmpty(unionUid)) {
            return true;
        }
        UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        if (unionInfo == null) {
            return true;
        }
        Map<Long, CrossUnionMember> unionMemberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
        if (unionMemberMap == null) {
            return true;
        }
        WingRoomProto.GetUnionMemberEventReqCrossMsg.Builder reqCrossMsg = WingRoomProto.GetUnionMemberEventReqCrossMsg.newBuilder();
        for (UnionMember member : unionMemberMap.values()) {
            if (relativeMap.containsKey(member.getUserId())) {
                continue;
            }
            long memberUserId = member.getUserId();
            if (memberUserId == player.getUserId()) {
                continue;
            }
            CrossUnionMember memberUserInfo = CrossUnionMgr.getUnionMember(memberUserId);
            if (memberUserInfo != null) {
                if (memberUserInfo.getServerId() != GameServer.getInstance().getServerId()) {
                    boolean isFind = false;
                    for(WingRoomProto.UnionMemberBaseInfoMsg tempMsg : crossReq.getMemberList()){
                        if(tempMsg.getUserId() == memberUserId){
                            isFind = true;
                            break;
                        }
                    }
                    if(isFind){
                        continue;
                    }
                    WingRoomProto.UnionMemberBaseInfoMsg.Builder builder = WingRoomProto.UnionMemberBaseInfoMsg.newBuilder();
                    builder.setUserId(memberUserId);
                    builder.setPlayerBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(memberUserInfo.getUserBaseInfo()));
                    reqCrossMsg.addMember(builder);
                    continue;
                }
            }
            UserWingRoomShareEvent event = shareEventMap.get(memberUserId);
            if (event == null) {
                continue;
            }
            UserInfo userInfo = UserMgr.getUserInfo(memberUserId);
            if (userInfo == null) {
                continue;
            }
            WingRoomProto.WingRoomFriendTemp.Builder friendTemp = WingRoomPb.buildWingRoomFriendTemp(player.getUserId(), memberUserId, userInfo, event, false);
            relativeMap.put(memberUserId, friendTemp);
        }
        if(crossReq.getMemberList().size() > 0){
            reqCrossMsg.addAllMember(crossReq.getMemberList());
        }
        if (reqCrossMsg.getMemberCount() > 0) {
            for (WingRoomProto.WingRoomFriendTemp.Builder builder : relativeMap.values()) {
                reqCrossMsg.addFriend(builder);
            }
            YanQuMessage message = YanQuMessageUtils.buildMessage(CrossProtocol.C_WING_ROOM_GET_UNION_MEMBER_EVENT, reqCrossMsg);
            GamePlayerMgr.sendPacket(player.getUserId(), message);
            return false;
        }
        return true;
    }

    /**
     * 技能等级上限提升
     * @return
     */
    public static int getSkillMaxLevelAdd(UserWingRoomData wingRoomData) {
        int addLv = 0;
        if (wingRoomData == null) {
            return addLv;
        }
        WingRoomLvConfig wingRoomLvConfig = WingRoomConfigMgr.getWingRoomLvConfig(wingRoomData.getLv());
        if (wingRoomLvConfig != null) {
            for (Integer skillId : wingRoomLvConfig.getSkillList()) {
                SkillInfo skillInfo = SkillMgr.getSkillInfo(skillId);
                if (skillInfo != null && skillInfo.getType() == eSkillType.SkillMaxLevelAdd.getValue()) {
                    addLv += SkillMgr.getSkillAddition(skillInfo, wingRoomData.getLv());
                }
            }
        }
        return addLv;
    }


    public static Map<Integer, UserPatrons> getTopUserPatrons(long visitor) {
        GamePlayer visitPlayer = GamePlayerMgr.getOnlinePlayer(visitor);
        Map<Integer, UserPatrons> patronsMap;
        if(visitPlayer == null){
            //不在线
            patronsMap = UserPatronsBussiness.getUserPatronsMap(visitor);
        }else {
            //在线
            patronsMap = visitPlayer.getModule(PatronsModule.class).getUserPatronsMap();
        }
        List<UserPatrons> list = new ArrayList<>(patronsMap.values());
        list.sort((o1, o2) -> o2.getAbility().compareTo(o1.getAbility()));
        //按职业取top
        Map<Integer, UserPatrons> resultMap = new HashMap<>();
        for (UserPatrons userPatrons : list) {
            PatronsInfo patronsInfo = PatronsMgr.getPatronsInfo(userPatrons.getPatronsId());
            if(patronsInfo != null){
                if(!resultMap.containsKey(patronsInfo.getOccupation())){
                    resultMap.put(patronsInfo.getOccupation(), userPatrons);
                }
            }
        }
        return resultMap;
    }

    public static void getAllFriendMap(List<Long> userList, Map<Long, Set<Long>> friendMap) {
        for (long userId : userList) {
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
            if(player == null){
                continue;
            }

            Map<Long, RelativesInfo> relativesMap = player.getModule(RelativesModule.class).getRelativesMap();
            long serverId = GameServer.getInstance().getServerId();
            for (Map.Entry<Long, RelativesInfo> entry : relativesMap.entrySet()) {
                RelativesInfo relativesInfo = entry.getValue();
                long relativeUserId = entry.getKey();
                if (relativesInfo != null && relativesInfo.getStatus() == 1) {
                    long relativesServerId = RelativesMgr.getUserServerId(relativeUserId);
                    if(relativesServerId == 0){
                        relativesServerId = serverId;
                    }
                    friendMap.computeIfAbsent(relativesServerId, k -> new HashSet<>());
                    friendMap.get(relativesServerId).add(relativeUserId);
                }
            }
            if(StringUtils.isNullOrEmpty(player.getUserInfo().getUnionUid())){
                continue;
            }
            Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(player.getUserInfo().getUnionUid());
            for (Map.Entry<Long, CrossUnionMember> entry : memberMap.entrySet()) {
                if(entry.getValue().getUserId() == userId){
                    continue;
                }
                friendMap.computeIfAbsent(entry.getValue().getServerId(), k -> new HashSet<>());
                friendMap.get(entry.getValue().getServerId()).add(entry.getKey());
            }
        }
    }
}
